const express = require('express')
const { json, type } = require('express/lib/response')
const router = express.Router()

const Phone = require('../Schemas/PhoneSchema')
const TbPhone = require('../Schemas/TaobaoSchema')
const SnPhone = require('../Schemas/SuningSchema')
const AuPhone = require('../Schemas/AthorSchema')
//分页查询数据
/**
 * page_size :每页的个数
 * page_now :现在的页数
 * condi:'查询条件'
 * newcondi:构造mongodb数组查询模块
 */
router.post('/queryList', (req, res) => {
    let condi = req.body.condi;
    let newcondi = [{
        sortcondi: {
            price: 0,
            ostime: 0,
            commentCounts: 0,
        }
    }]
    if (condi.skuname) {
        newcondi.push(
            // { skuname: { $regex: condi.skuname } }
            { $or: [{ skuname: { $regex: condi.skuname } }, { brand: { $regex: condi.skuname } }] }
        )
    }
    ;
    if (condi.brand) {
        if (condi.skuname) {
            newcondi.forEach(p => {
                if (p.$or) {
                    newcondi.pop(p)
                }
            })
        }

        newcondi.push({ brand: condi.brand })
    }
    if (condi.cpu) {
        newcondi.push({ cpu: condi.cpu })
    }
    if (condi.ceamra) {
        console.log(typeof condi.ceamra);
        newcondi.push({ rearcamera: condi.ceamra })
    }
    if (condi.system) {
        newcondi.push({ system: condi.system })
    }
    if (condi.screen.length != 0) {
        console.log(condi.screen);
        if (condi.screen.length == 1) {
            console.log(condi.screen);
            newcondi.push({ screen: 0 })
        } else {
            newcondi.push({ screen: { $gt: condi.screen[0], $lt: condi.screen[1] } })
        }
    }
    if (condi.price.length != 0) {
        newcondi.push({ price: { $gt: condi.price[0], $lt: condi.price[1] } })
    }
    if (condi.ram != -1) {
        newcondi.push({ proRam: condi.ram })
    }
    if (condi.rom != -1) {
        newcondi.push({ proRom: condi.rom })
    }
    if (condi.adprice != 0) {
        newcondi[0].sortcondi.price = condi.adprice
    } if (condi.ostime != 0) {
        newcondi[0].sortcondi.ostime = condi.ostime
    } if (condi.commentCounts != 0) {
        newcondi[0].sortcondi.commentCounts = condi.commentCounts
    }
    Object.keys(newcondi[0].sortcondi).map((key) => {
        if (newcondi[0].sortcondi[key] == 0) delete newcondi[0].sortcondi[key];
    });
    let skips = (req.body.page_now - 1) * 20
    if (newcondi.length == 1) {
        Phone.find().then(phone => {
            Phone.find().sort(newcondi[0].sortcondi).skip(skips).limit(20).exec((err, data) => {
                if (err) {
                    res.json({
                        code: 502,
                        message: "查询失败",
                        data: {
                            err
                        }
                    })
                } else {
                    res.json({
                        code: 200,
                        message: 'OK',
                        data: {
                            page_now: req.body.page_now,
                            total: phone.length,
                            data: data
                        }
                    })
                }
            })
        })
    } else {
        Phone.find({ $and: newcondi }).then(phone => {
            Phone.find({ $and: newcondi }).sort(newcondi[0].sortcondi).skip(skips).limit(20).exec((err, data) => {
                if (err) {
                    res.json({
                        code: 502,
                        message: "查询失败",
                        data: {
                            err
                        }
                    })
                } else {
                    res.json({
                        code: 200,
                        message: 'OK',
                        data: {
                            page_now: req.body.page_now,
                            total: phone.length,
                            data: data
                        }
                    })
                }
            })
        })
    }

})

router.post('/serachPhone', (req, res) => {
    Phone.find({}).then(p => {
        res.json({
            code: 200,
            message: "查询成功",
            data: p
        })
    })
})

/*
* 获取数据库的所有品牌
* 运行内存
* 机身内存
*/
router.get('/getBrands', (req, res) => {
    Phone.find({}).then(phones => {
        let brands = []
        let ram = []
        let rom = []
        let cpu = []
        let rearcamera = []
        let system = []
        phones.forEach(p => {
            brands.push(p.brand)
            ram.push(p.proRam)
            rom.push(p.proRom)
            cpu.push(p.cpu)
            rearcamera.push(p.rearcamera)
            system.push(p.system)
        })
        brands = [...new Set(brands)]
        cpu = [...new Set(cpu)]
        rearcamera = [...new Set(rearcamera)]
        rearcamera.sort((a, b) => {
            function toNum(s) {
                if (s == ' ' || s == '其他' || s == '无后置摄像头') {
                    s = 0
                } else {
                    s = s.replace('万像素', '0000')
                    s = s.replace('亿像素', '00000000')
                }
                return parseInt(s)
            }

            return toNum(b) - toNum(a)
        })
        system = [...new Set(system)]
        ram = [...new Set(ram)]
        ram.sort((a, b) => { return b - a }
        )
        rom = [...new Set(rom)]
        rom.sort((a, b) => { return b - a }
        )
        res.json({
            code: 200,
            message: 'OK',
            brands,
            ram,
            rom,
            cpu,
            rearcamera,
            system
        })
    }).catch(() => {
        res.json({
            code: 500,
            message: '更新失败'
        })
    })
})

//字符串匹配度算法
var diffStr = function (str1, str2) {
    // 计算两个字符串长度
    const len1 = str1.length;
    const len2 = str2.length;

    // 创建装载数组
    const dif = [];
    for (let i = 0; i < len1 + 1; i++) {
        dif.push(new Array(len2 + 1));
    }
    // 赋初始值
    for (let i = 0; i <= len1; i++) {
        dif[i][0] = i;
    }
    for (let i = 0; i <= len2; i++) {
        dif[0][i] = i;
    }
    // 计算两个字符串是否一样
    const ch1 = str1.split('');
    const ch2 = str2.split('');
    let temp;
    for (let i = 1; i <= len1; i++) {
        for (let j = 1; j <= len2; j++) {
            if (ch1[i - 1] == ch2[j - 1]) {
                temp = 0;
            } else {
                temp = 1;
            }
            // 取最小值
            const temp1 = dif[i - 1][j - 1] + temp;
            const temp2 = dif[i][j - 1] + 1;
            const temp3 = dif[i - 1][j] + 1;

            dif[i][j] = Math.min(temp1, temp2, temp3);
        }
    }
    // 计算相似度
    const similarity = (Math.max(str1.length, str2.length) - dif[len1][len2]) / Math.min(str1.length, str2.length);
    return similarity;
}
var diffbrand = (str1, str2) => {
    let x = str1.split(" ");
    let y = str2.split(" ");
    let ans = 0;
    let ret = 0;
    for (let i = 0; i < x.length; i++) {
        for (let j = 0; j < y.length; ++j) {
            if (x[i] === undefined || y[j] === undefined) {
                // console.log("continue");
                continue;
            }
            if (x[i].indexOf(y[j]) >= 0 || y[j].indexOf(x[i]) >= 0) {
                ans++;
                // console.log(x[i], '   x', i, x.length);
                // console.log(y[j], '     y', j);
                // console.log(str1, '    str1');
                // console.log(str2, '    str2');
                ret += Math.min(x[i].length, y[j].length);
            }
        }
    }
    return [ans, ret]
}
//获取详情页信息
router.get('/getOneProduct', (req, res) => {
    let sortP = {
        taobao: '',
        suning: '',
        guanfan: '',
    }
    let skuid = Number(req.query.skuid)
    Phone.findOne({ skuid: skuid }).then((p) => {
        sortP.jidong = {
            comment: p.comment[0]['CommentCountStr'],
            price: p.price,
            img: ` https://img11.360buyimg.com/n7/${p.imageList[0]}`,
            url: `https://item.jd.com/${p.skuid}.html`,
            logourl: p.logourl
        }
        brand = p.brand.split('（')[0]
        jixing = p.jixing.trim()
        TbPhone.find({ skuname: { $regex: brand } }).then((x) => {
            if (x != null) {
                x.sort((a, b) => {
                    let bb = diffbrand(b.skuname, jixing);
                    let aa = diffbrand(a.skuname, jixing);
                    if (aa[0] === bb[0]) {
                        return bb[1] - aa[1];
                    }
                    else return bb[0] - aa[0];
                })
                sortP.taobao = x[0]

            } else {
                sortP.taobao = x
            }
            if (sortP.suning != '' && sortP.guanfan != '') {
                res.json({
                    code: 200,
                    message: '查询成功',
                    data: p,
                    sortP: sortP
                })
            }
        })
        SnPhone.find({ skuname: { $regex: brand } }).then(x => {
            if (x != null) {
                x.sort((a, b) => {
                    let bb = diffbrand(b.skuname, jixing);
                    let aa = diffbrand(a.skuname, jixing);
                    if (aa[0] === bb[0]) {
                        return bb[1] - aa[1];
                    }
                    else return bb[0] - aa[0];
                })
                // console.log(x.slice(0, 10));
                // console.log(x);
                sortP.suning = x[0]
            } else {
                sortP.suning = x
            }
            if (sortP.taobao != '' && sortP.guanfan != '') {
                res.json({
                    code: 200,
                    message: '查询成功',
                    data: p,
                    sortP: sortP
                })
            }
        })
        AuPhone.find({ brand: p.brand }).then(x => {
            if (x != null) {
                x.sort((a, b) => {
                    let bb = diffbrand(b.skuname, jixing);
                    let aa = diffbrand(a.skuname, jixing);
                    if (aa[0] === bb[0]) {
                        return bb[1] - aa[1];
                    }
                    else return bb[0] - aa[0];
                })
                sortP.guanfan = x[0]
            } else {
                sortP.guanfan = x
            }
            if (sortP.taobao != '' && sortP.suning != '') {
                res.json({
                    code: 200,
                    message: '查询成功',
                    data: p,
                    sortP: sortP
                })
            }
        })
    }).catch((err) => {
        //console.log(err);
        res.json({
            code: 500,
            message: '更新失败'
        })
    });
})

//
// router.get('/updatesome', (req, res) => {
//     AuPhone.find({ brand: 'Apple' }).then(p => {
//         p.forEach(x => {
//             price = Number(x.price)
//             AuPhone.updateOne({ _id: x._id.toString() }, {
//                 $set: {
//                     price: price
//                 }
//             }).then(y => {
//                 console.log(y);
//             })
//         })
//     })

// })
router.get('/updatesome', (req, res) => {
    AuPhone.find({ brand: 'vivo' }).then(x => {
        x.sort((a, b) => {
            return diffStr(b.skuname, ' vivoiQOO 9') - diffStr(a.skuname, ' vivoiQOO 9')
        })
        x.forEach(e => {
            console.log(e.skuname);
        })
    })

})

router.get('/updateRam', (req, res) => {
    // Phone.find({ proRam: '2GB以下' }).then(p => {
    //     p.forEach(e => {
    //         Phone.up
    //     })
    // })
    Phone.updateMany({ proRam: '2GB以下' }, {
        $set: {
            proRam: 1
        }
    }).then(res => {
        console.log(res);
    })
})

router.get('/updateCpu', (req, res) => {
    Phone.find().then(p => {
        p.forEach(a => {
            let cpu = ''
            let rearcamera = ' '
            let system = ''
            a.product_info.forEach(e => {

                if (e.indexOf('CPU型号') != -1) {
                    cpu = e.split('：')[1]
                }
                if (e.indexOf('后摄主摄像素') != -1) {
                    rearcamera = e.split('：')[1]
                }
                if (e.indexOf('系统') != -1) {
                    system = e.split('：')[1]
                }

            })
            Phone.updateOne({ skuid: a.skuid }, {
                $set: {
                    cpu: cpu,
                    rearcamera,
                    system
                }
            }).then(p => {
                console.log(p);
            })
        })

    })
    // Phone.find({ rearcamera: '1300万像素' }).then(p => {
    //     p.forEach(e => {
    //         console.log(e.rearcamera);
    //     })
    // })
})
module.exports = router

/*
0
0
10299
1049
1049
 */